<template>
  <div class="add_dept">
    <el-dialog
      :title="isShows"
      :visible="isShow"
      @close="handleClose"
      @open="getHeadDepartment"
    >
      <!-- 表单 -->
      <el-form
        label-width="120px"
        :model="newObjList"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="newObjList.name"
            style="width: 90%"
            placeholder="1-50个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input
            v-model="newObjList.code"
            style="width: 90%"
            placeholder="1-50个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select
            placeholder="请选择"
            style="width: 90%"
            v-model="newObjList.manager"
          >
            <el-option
              v-for="item in HeadList"
              :key="item.id"
              :value="item.username"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="newObjList.introduce"
            type="textarea"
            style="width: 90%"
            placeholder="1-300个字符"
            autocomplete="off"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <template slot="footer">
        <el-button type="primary" size="small" @click="handleSubmit"
          >确定</el-button
        >
        <el-button size="small" @click="handleClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getHeadDepartmentApi,
  getNewDepartmentApi,
  getDetailDepartmentApi,
  updatedDetailDepartmentApi,
} from "@/api/departments";
export default {
  name: "Add_Dept",
  props: {
    // 控制弹框的隐藏的数据
    isShow: {
      type: Boolean,
      default: false,
    },
    nodeData: {
      type: Object,
      required: true,
    },
    //列表数据
    deptList: {
      type: Array,
      // 引用类型需要写成函数的格式，返回值才是默认值
      default: () => [],
    },
  },
  data() {
    // 自定义校验
    const validateName = (rule, value, callback) => {
      const flag = this.nodeData.isShows
        ? this.deptList.some((item) => item.name === value)
        : this.deptList
            .filter((item) => item.id !== this.nodeData.id)
            .some((item) => item.name === value);
      flag ? callback(new Error(`${value}部门已存在`)) : callback();
    };
    const validateCode = (rule, value, callback) => {
      const flag = this.nodeData.isShows
        ? this.deptList.some((item) => item.name === value)
        : this.deptList
            .filter((item) => item.id !== this.nodeData.id)
            .some((item) => item.name === value);
      flag ? callback(new Error(`${value}编码已存在`)) : callback();
    };
    return {
      // 收集用户输入的信息
      newObjList: {
        code: "",
        introduce: "",
        manager: "",
        name: "",
      },
      // 部门负责人列表
      HeadList: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "部门名称必填", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{1,10}$/,
            message: "部门名称要求1-10个字符",
            trigger: "blur",
          },
          { validator: validateName, trigger: "blur" },
        ],
        code: [
          { required: true, message: "部门编码必填", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9_]{1,50}$/,
            message: "部门编码要求1-50个字符",
            trigger: "blur",
          },
          { validator: validateCode, trigger: "blur" },
        ],
        manager: [
          { required: true, message: "部门负责人必选", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍必填", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{1,300}$/,
            message: "格式不能为特殊符号",
            trigger: "blur",
          },
        ],
      },
    };
  },

  methods: {
    // 通知父级关闭弹层
    handleClose() {
      // 重置表单
      this.$refs.ruleForm.resetFields();
      this.$emit("update:isShow", false);
    },
    // 获取部门负责人列表
    async getHeadDepartment() {
      if (!this.HeadList.length) {
        const resp = await getHeadDepartmentApi();
        this.HeadList = resp.data;
      }
      // this.nodeData.isShows为false 时进入编辑模式
      if (!this.nodeData.isShows) {
        const { data } = await getDetailDepartmentApi(this.nodeData.id);
        this.newObjList = {
          ...data,
        };
      }
    },

    // 添加部门/编辑部门
    handleSubmit() {
      this.$refs.ruleForm.validate(async (valia) => {
        if (!valia) return;
        if (this.nodeData.isShows) {
          const newObj = {
            ...this.newObjList,
            // this.nodeData.manager有值添加的不是一级部门
            pid: this.nodeData.manager ? this.nodeData.id : "",
          };
          await getNewDepartmentApi(newObj);
        } else {
          // this.nodeData.isShows为false 时进入编辑模式
          await updatedDetailDepartmentApi(this.newObjList);
        }

        // 通知父组件重新渲染页面
        this.$emit("Re-render");
        // 关闭弹层清空表单
        this.handleClose();
        // 获取部门列表
        // this.parent: 获取某个组件的父组件(对象)
        // this.children: 获取某个组件的所有子组数组(对象)
      });
    },
  },
  computed: {
    // 动态切换title
    isShows() {
      return this.nodeData.isShows ? "新增部门" : "编辑部门";
    },
  },
};
</script>

<style>
</style>